package org.piggy.gateway;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.util.AttributeKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;

public class HttpClient {
    private final static Logger logger = LoggerFactory.getLogger(HttpClient.class);

    public final static String attr = "responseChannel";

    private final static Bootstrap bootstrap;

    private final static NioEventLoopGroup group;

    static {
        group = new NioEventLoopGroup();
        bootstrap = new Bootstrap();
        bootstrap.group(group).channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) {
                        ChannelPipeline p = ch.pipeline();
                        p.addLast(new HttpClientCodec());
                        p.addLast(new HttpObjectAggregator(8192));
                        p.addLast(new ChannelInboundHandlerAdapter(){
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) {
                                logger.info("HttpClient.channelRead.hashcode -> {}", ctx.channel().hashCode());

                                FullHttpResponse response = (FullHttpResponse) msg;
                                logger.info("response body -> " + response.content().toString(io.netty.util.CharsetUtil.UTF_8));
                                // 异步
                                Channel respChannel = (Channel) ctx.channel().attr(AttributeKey.valueOf(attr)).get();
                                respChannel.writeAndFlush(response);

                            }
                            @Override
                            public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
                                cause.printStackTrace();
                                ctx.channel().close();
                            }
                        });
                    }
                });
    }

    public static ChannelFuture getChannelFuture() {
        try {
            return bootstrap.connect(Config.getConfigParam().getTargetIp(), Config.getConfigParam().getTargetPort()).syncUninterruptibly();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
